package dao

import (
	"gorm.io/gorm"
	"view-crawler-backend/internal/dao/entity"
	"view-crawler-backend/internal/tools"
)

func DeleteTaskById(db *gorm.DB, taskId int64) error {
	return db.Table("task").Where("task_id = ?", taskId).Delete(&entity.Task{}).Error
}

func AddTask(db *gorm.DB, task *entity.Task) error {
	return db.Table("task").Create(task).Error
}

func UpdateTask(db *gorm.DB, task *entity.Task) error {
	return db.Table("task").Where("task_id =?", task.TaskId).Updates(task).Error
}

func QueryTaskCount(db *gorm.DB) (int64, error) {
	var count int64
	if err := db.Table("task").Count(&count).Error; err != nil {
		return 0, err
	}
	return count, nil
}

func QueryTaskList(db *gorm.DB, page, pageSize int) ([]entity.Task, error) {
	var tasks []entity.Task
	if err := db.Table("task").Scopes(tools.Paginate(page, pageSize)).Find(&tasks).Error; err != nil {
		return nil, err
	}
	return tasks, nil
}

func QueryTaskByTaskId(db *gorm.DB, taskId int64) (*entity.Task, error) {
	task := entity.Task{}
	if err := db.Table("task").Where("task_id = ?", taskId).First(&task).Error; err != nil {
		return nil, err
	}
	return &task, nil
}

func QueryTaskExecTimesById(db *gorm.DB, taskId int64) (int, error) {
	task := entity.Task{}
	if err := db.Table("task").Select("task_exec_times").Where("task_id = ?", taskId).First(&task).Error; err != nil {
		return 0, err
	}
	return task.TaskExecTimes, nil
}

func IsTaskNameInUse(db *gorm.DB, taskName string) (bool, error) {
	var count int64
	if err := db.Table("task").Where("task_name =?", taskName).Count(&count).Error; err != nil {
		return false, err
	}
	return count > 0, nil
}

func IncreaseTaskExecTimes(db *gorm.DB, taskId int64) error {
	return db.Table("task").Where("task_id =?", taskId).Update("task_exec_times", gorm.Expr("task_exec_times + ?", 1)).Error
}
